package com.caotv.wkreport.action;

import org.apache.struts2.ServletActionContext;

import com.caotv.wkreport.dao.*;
import com.caotv.wkreport.dbutils.UserTableTool;
import com.caotv.wkreport.utils.StringUtils;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @author cao
 *
 */

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private User user;
	
	public String execute() {
		ServletActionContext.getRequest().getSession().setAttribute("loggedInUser", user);
		return "success";
	}	

	public void validate() {
		if (StringUtils.isNullOrEmpty(username)) {
			addFieldError("username", getText("errors.userreq"));
		} else if (StringUtils.isNullOrEmpty(password)) {
			addFieldError("password", getText("errors.passreq"));
		} else {
			user = UserTableTool.getInstance().getUserByUsername(username);
			if (StringUtils.isNullOrEmpty(user)) {
				addFieldError("username", getText("errors.invalid"));
			} else {
				if (!password.equals(user.getPassword())){
					addFieldError("username", getText("errors.invalid"));
				}
			}
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
